package org.hit.burkun.extract;

import java.util.Collection;
import java.util.LinkedList;

import org.hit.burkun.db.DBHelper;
import org.hit.burkun.db.DBTypeConverter;
import org.hit.burkun.dbimport.MemoryImport;
import org.hit.burkun.entities.realtions.BaseRealtion;
import org.hit.burkun.entities.realtions.BaseRealtionDBConfigure;

public class RelationDump {
	public static int curPid = 0;

	// 保存到数据库，如果是单向的，那么存入数据，且翻转后再存一遍
	public static void dumpRelations(Collection<BaseRealtion> baseRel,
			boolean inverseRel, String tbName) {
		Collection<String[]> pipline = new LinkedList<>();
		for (BaseRealtion br : baseRel) {
			pipline.add(BaseRealtionDBConfigure.dumpDBArray(br));
			// 是不是双向的，且两个点不一致
			if (inverseRel
					&& !br.isDirect()
					&& !br.getEnt1().getPrimary_id()
							.equals(br.getEnt2().getPrimary_id())) {
				pipline.add(BaseRealtionDBConfigure.dumpReverseDBArray(br));
			}
		}
		DBTypeConverter typeConverter = new DBTypeConverter(
				BaseRealtionDBConfigure.getDbDataTypes());

		MemoryImport imp = new MemoryImport(tbName, DBHelper.getServerData(),
				true, typeConverter);
		curPid = imp.doImport(pipline, curPid); // 能够保证pid唯一
	}

	// 不带自增的
	public static void dumpRelationsWithoutPrimaryId(
			Collection<BaseRealtion> baseRel, boolean inverseRel, String tbName) {
		Collection<String[]> pipline = new LinkedList<>();
		for (BaseRealtion br : baseRel) {
			pipline.add(BaseRealtionDBConfigure.dumpDBArray(br));
			// 是不是双向的，且两个点不一致
			if (inverseRel
					&& !br.isDirect()
					&& !br.getEnt1().getPrimary_id()
							.equals(br.getEnt2().getPrimary_id())) {
				pipline.add(BaseRealtionDBConfigure.dumpReverseDBArray(br));
			}
		}
		DBTypeConverter typeConverter = new DBTypeConverter(
				BaseRealtionDBConfigure.getDbDataTypesWithoutPid());

		MemoryImport imp = new MemoryImport(tbName, DBHelper.getServerData(),
				false, typeConverter);
		imp.doImport(pipline, BaseRealtionDBConfigure.getFields());
	}

}
